package com.zmn.oms.admin.controller.redistribute;

import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.mcc.permit.client.annotation.FilterPermitData;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.business.interfaces.conf.distributereason.ConfOrderDistributeReasonBService;
import com.zmn.oms.common.constant.ConfRedistributeConsts;
import com.zmn.oms.common.constant.OrderDistributeConsts;
import com.zmn.oms.common.dio.redistribute.OrderWorkRedistributeApplyQuery;
import com.zmn.oms.common.dio.redistribute.RedistributeServingDuplicateOrderDIO;
import com.zmn.oms.common.dro.conf.distribute.DistributeConfigDRO;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.enums.RedistributeAuditStatusEnum;
import com.zmn.oms.common.enums.RedistributeStatusEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.entity.conf.distributereason.ConfOrderDistributeReasonQuery;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.redistribute.OrderWorkRedistributeApply;
import com.zmn.oms.model.entity.work.DistributeMasterQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.query.redistribute.OrderWorkRedistributeQuery;
import com.zmn.oms.model.vo.conf.distributereason.ConfOrderDistributeReasonVO;
import com.zmn.oms.model.vo.redistribute.OrderWorkRedistributeInfoVO;
import com.zmn.oms.model.vo.redistribute.OrderWorkRedistributeMasterVO;
import com.zmn.oms.model.vo.redistribute.RedistributeApplyVO;
import com.zmn.oms.model.vo.work.DistributeReasonVO;
import com.zmn.oms.model.vo.work.DistributeVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.redistribute.OrderWorkRedistributeApplyService;
import com.zmn.oms.services.interfaces.redistribute.OrderWorkRedistributeInfoService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.redistribute.OrderWorkRedistributeInfoBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 类描述: 工单改派查询 Controller类
 *
 * @author: liudi
 * @since: 2022/05/11 12:00
 */
@Controller
@RequestMapping("/work/redistribute")
@Slf4j
public class OrderWorkRedistributeListController extends OmsBaseController {

	@Resource
	private OrderWorkRedistributeInfoBService redistributeInfoBService;
	@Resource
	private OrderWorkRedistributeApplyService orderWorkRedistributeApplyService;
	@Resource
	private OrderWorkRedistributeInfoService orderWorkRedistributeInfoService;
	@Resource
	private ConfOrderDistributeReasonBService confOrderDistributeReasonBService;
	@Resource
	private ZsDistributeWorkBService zsDistributeWorkBService;
	@Resource
	private OrderWorkService orderWorkService;
	@Resource
	private OrderDetailService orderDetailService;

	/**
	 * 跳转到改派列表页面
	 *
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView jumpRedistributeListPage(Long orderId, ModelAndView mv) {
		mv.setViewName("redistribute/list");
		mv.addObject("orderId", orderId);
		mv.addObject("staffId", getCurrentStaff().getStaffId());

		// 导出权限
		mv.addObject("exportPermit", StaffAdminService.isPermitted(ConfRedistributeConsts.ODP_APPLY_LIST_EXPORT));
		return mv;
	}

	/**
	 * 跳转到改派【详情/审核/备注】页面
	 *
	 * @param id   改派申请Id
	 * @param type 页面类型 1.详情 2.审核 3.备注
	 * @return
	 */
	@RequestMapping(value = "/detail")
	public ModelAndView detail(ModelAndView mv, Long id, Integer type) {
		mv.setViewName("redistribute/detail");
		OrderWorkRedistributeInfoVO redistributeInfoVO = redistributeInfoBService.getRedistributeInfoVOById(id);
		this.setDistributeReasonList(mv, redistributeInfoVO.getType(), type);

		mv.addObject("type", type);
		mv.addObject("infoVo", redistributeInfoVO);
		mv.addObject("cityList", super.getAllCityList());
		mv.addObject("provinceList", super.getAllProvinceList());
		return mv;
	}

	/**
	 * 查询列表 ajax
	 */
	@FilterPermitData
	@RequestMapping(value = "/ajax/list")
	@ResponseBody
	public ResultDTO ajaxList(@RequestBody OrderWorkRedistributeQuery query) {
		List<OrderWorkRedistributeInfoVO> redistributeInfoVOList = redistributeInfoBService.listPageByQuery(query);
		LayuiTableDO<OrderWorkRedistributeInfoVO> data = new LayuiTableDO();
		data.setCount(query.getTotalCount());
		data.setData(redistributeInfoVOList);
		return ResultDTO.success(data);
	}

	/**
	 * 获取该订单对应的“待改派申请”信息
	 *
	 * @param orderId
	 * @param workId
	 * @return
	 */
	@RequestMapping(value = "/getWaitRedistributeApply")
	@ResponseBody
	public ResultDTO<RedistributeApplyVO> getWaitRedistributeApply(Long orderId, Long workId) {
		RedistributeApplyVO vo = new RedistributeApplyVO();

		OrderWorkRedistributeApplyQuery query = new OrderWorkRedistributeApplyQuery();
		query.setOrderId(orderId);
		query.setWorkId(workId);
		query.setRedistributeStatus(RedistributeStatusEnum.WAIT_REDISTRIBUTE.getCode());
		List<OrderWorkRedistributeApply> applyList = orderWorkRedistributeApplyService.listByQuery(query);
		if (CollectionUtil.isNotNullOrEmpty(applyList)) {
			vo = BeanMapper.map(applyList.get(0), RedistributeApplyVO.class);
		}
		return ResultDTO.success(vo);
	}


	/**
	 * 工单列表导出 ajax
	 */
	@FilterPermitData
	@PostMapping("/list/export/async")
	@ResponseBody
	public ResultDTO ajaxListExportAsync(@RequestBody OrderWorkRedistributeQuery query) {
		if (!StaffAdminService.isPermitted(ConfRedistributeConsts.ODP_APPLY_LIST_EXPORT)) {
			return ResultDTO.fail("无权限操作！");
		}
		// 最大一万条
		query.setPageSize(10000);
		try {
			redistributeInfoBService.buildExportTask(query);
		} catch (OmsBaseException e) {
			return ResultDTO.fail(e.getMessage());
		}
		return ResultDTO.success();
	}


	/**
	 * 获取可改派的工程师列表 ajax
	 */
	@RequestMapping(value = "/listRedistributeEngineer")
	@ResponseBody
	public ResultDTO listRedistributeEngineer(Long orderId, Long workId) {
		List<OrderWorkRedistributeMasterVO> masterVOList = redistributeInfoBService.listRedistributeEngineer(orderId, workId);
		return ResultDTO.success(masterVOList);
	}


	/**
	 * 解密信息
	 *
	 * @param redistributeId 改派申请Id
	 * @param type           1：用户联系电话 2:用户地址 3.工程师手机号
	 * @param phoneIndex     第几个号码
	 * @param addressType    地址类型：1.改派地址 2. 订单地址
	 * @return
	 */
	@GetMapping(value = "/show/hideInfo")
	@ResponseBody
	public ResultDTO showDetailHideInfo(Long redistributeId, Integer type, Integer phoneIndex, Integer addressType) {
		Objects.requireNonNull(redistributeId, "改派ID不能为空！");
		OrderWorkRedistributeInfoVO infoVO = orderWorkRedistributeInfoService.findApplyInfoByRedistributeId(redistributeId);

		if (Objects.isNull(infoVO)) {
			return ResultDTO.fail("获取信息失败，请稍后重试");
		}

		// 联系电话
		if (Objects.equals(1, type)) {
			if (Objects.isNull(phoneIndex)) {
				phoneIndex = 1;
			}
			String telephone = "";
			switch (phoneIndex) {
				case 1:
					telephone = infoVO.getTelephone();
					break;
				case 2:
					telephone = infoVO.getTelephone2();
					break;
				case 3:
					telephone = infoVO.getTelephone3();
					break;
			}


			String[] split = telephone.split("-");
			if (split.length == 2 && StringUtil.isMobile(split[0])) {
				// 是分机电话，只需要显示电话
				telephone = split[0];
			}

			return ResultDTO.success(telephone);
		}

		// 用户地址
		if (Objects.equals(2, type)) {
			String address = "";

			switch (addressType) {
				case 1:
					address = String.join(" ",
							infoVO.getProvinceName(),
							infoVO.getCityName(),
							infoVO.getCountyName(),
							infoVO.getStreet(),
							StringUtils.defaultString(infoVO.getAddress()));
					break;
				case 2:
					OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(infoVO.getOrderId());
					address = String.join(" ",
							orderDetail.getProvinceName(),
							orderDetail.getCityName(),
							orderDetail.getCountyName(),
							orderDetail.getStreet(),
							StringUtils.defaultString(orderDetail.getAddress()));
					break;
				default:
					break;
			}

			return ResultDTO.success(address);
		}

		// 工程师手机号
		if (Objects.equals(3, type)) {
			return ResultDTO.success(infoVO.getMasterPhone());
		}

		return ResultDTO.success("");
	}


	/**
	 * 获取订单上的地址
	 *
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "/getOrderAddress")
	@ResponseBody
	public ResultDTO getOrderAddress(Long orderId) {
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

		if (Objects.nonNull(orderDetail)) {
			String address = String.join(" ",
					orderDetail.getProvinceName(),
					orderDetail.getCityName(),
					orderDetail.getCountyName(),
					orderDetail.getStreet(),
					StringUtils.defaultString(orderDetail.getAddress()));
			return ResultDTO.success(address);
		}

		return ResultDTO.fail("获取地址失败");
	}


	/**
	 * 检查是否能审核
	 */
	@RequestMapping(value = "/checkCanAudit")
	@ResponseBody
	public ResultDTO checkCanAudit(Long redistributeId) {
		OrderWorkRedistributeApply orderWorkRedistributeApply = orderWorkRedistributeApplyService.selectByPrimaryKey(redistributeId);
		if (!(Objects.equals(orderWorkRedistributeApply.getAuditStatus(), RedistributeAuditStatusEnum.WAIT_AUDIT.getCode())
				|| Objects.equals(orderWorkRedistributeApply.getAuditStatus(), RedistributeAuditStatusEnum.PROCESSING_AUDIT.getCode()))) {
			return ResultDTO.success(Boolean.FALSE);
		}
		return ResultDTO.success(Boolean.TRUE);
	}

	/**
	 * 检查是否有在途重复的订单
	 *
	 * @param dio 改派数据输入类
	 * @return Boolean 是否在途重复
	 */
	@RequestMapping(value = "/checkServingDuplicateOrder")
	@ResponseBody
	public ResultDTO checkServingDuplicateOrder(RedistributeServingDuplicateOrderDIO dio) {
		Boolean hasOnServingDuplicate = redistributeInfoBService.checkServingDuplicateOrder(dio);
		return ResultDTO.success(hasOnServingDuplicate);
	}

	/**
	 * 获取派单数据
	 *
	 * @param distributeMasterQuery
	 * @return
	 */
	@RequestMapping(value = "/getDistributeInfo")
	@ResponseBody
	public ResultDTO getDistributeInfo(DistributeMasterQuery distributeMasterQuery) {
		DistributeVO distributeVO = this.getGridDistributeMasterList(distributeMasterQuery);
		return ResultDTO.success(distributeVO);
	}

	/**
	 * 校验工程师是否可服务
	 *
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "/checkEngineer")
	@ResponseBody
	public ResultDTO checkEngineer(DistributeMasterQuery query) {
		try {
			OrderWork orderWork = orderWorkService.findOrderWorkByKey(query.getOrderId(), query.getWorkId());
			OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(query.getOrderId());

			DistributeMasterQuery distributeMasterQuery = zsDistributeWorkBService.buildDistributeMasterQuery(orderWork, orderDetail, true);
			distributeMasterQuery.setMasterId(query.getMasterId());

			if (NumberUtil.isNotNullOrZero(query.getProductId()) && !Objects.equals(query.getProductId(), orderWork.getProductId())) {
				distributeMasterQuery.setProductId(query.getProductId());
				distributeMasterQuery.setServCategId(query.getServCategId());
				distributeMasterQuery.setCategId(query.getCategId());
			}

			if ((Objects.nonNull(query.getLatitude()) && Objects.nonNull(query.getLongitude()))
					&& (!Objects.equals(query.getLatitude(), orderDetail.getLatitude()) || !Objects.equals(query.getLongitude(), orderDetail.getLongitude()))) {
				distributeMasterQuery.setLatitude(query.getLatitude());
				distributeMasterQuery.setLongitude(query.getLongitude());
				distributeMasterQuery.setCountyId(query.getCountyId());
				distributeMasterQuery.setStreetId(query.getStreetId());
			}

			DistributeConfigDRO distributeConfig = zsDistributeWorkBService.getDistributeConfig(orderWork);
			DistributeReasonVO distributeReasonVO = zsDistributeWorkBService.checkDistributeReason(distributeMasterQuery, distributeConfig, true);
			return ResultDTO.success(distributeReasonVO);
		} catch (Exception e) {
			log.error("改派-校验工程师是否可服务保错：{}", e.toString());
			return ResultDTO.fail(e.getMessage());
		}
	}


	/**
	 * 设置页面参数：核实的改派缘由
	 *
	 * @param mv
	 * @param orderType 订单类型：1 新单、2 返修单、3 退款单
	 * @param type      页面类型 1.详情 2.审核
	 */
	private void setDistributeReasonList(ModelAndView mv, Integer orderType, Integer type) {
		// 如果页面类型是【审核】
		if (Objects.equals(type, 2)) {
			ConfOrderDistributeReasonQuery query = new ConfOrderDistributeReasonQuery();
			query.setStatus(GlobalConsts.YES);
			query.setOrderType(String.valueOf(orderType));
			List<ConfOrderDistributeReasonVO> reasonList = confOrderDistributeReasonBService.listByQuery(query);
			mv.addObject("distributeReasonList", reasonList);
		}
	}


	/**
	 * 获取网格派单工程师列表
	 *
	 * @return
	 */
	private DistributeVO getGridDistributeMasterList(DistributeMasterQuery query) {
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(query.getOrderId(), query.getWorkId());
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(query.getOrderId());
		// 获取派单参数
		DistributeConfigDRO distributeConfigDRO = zsDistributeWorkBService.getDistributeConfig(orderWork);
		// 派单视图对象
		DistributeVO distributeVO = zsDistributeWorkBService.buildDistributeVO(orderWork, orderDetail, distributeConfigDRO.getPlatDirectlyDistributeArgsDRO(), true);
		// 设置派单路径为平台直派
		distributeVO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);

		DistributeMasterQuery distributeMasterQuery = zsDistributeWorkBService.buildDistributeMasterQuery(orderWork, orderDetail, true);
		if (NumberUtil.isNotNullOrZero(query.getProductId()) && !Objects.equals(query.getProductId(), orderWork.getProductId())) {
			distributeMasterQuery.setProductId(query.getProductId());
			distributeMasterQuery.setServCategId(query.getServCategId());
			distributeMasterQuery.setCategId(query.getCategId());
		}

		if ((Objects.nonNull(query.getLatitude()) && Objects.nonNull(query.getLongitude()))
				&& (!Objects.equals(query.getLatitude(), orderDetail.getLatitude()) || !Objects.equals(query.getLongitude(), orderDetail.getLongitude()))) {
			distributeMasterQuery.setLatitude(query.getLatitude());
			distributeMasterQuery.setLongitude(query.getLongitude());
			distributeMasterQuery.setCountyId(query.getCountyId());
			distributeMasterQuery.setStreetId(query.getStreetId());
		}

//		zsDistributeWorkBService.gridGetOrderRedistributeVO(orderWork, orderDetail, distributeVO, distributeConfigDRO);
		zsDistributeWorkBService.gridGetOrderRedistributeVO(distributeMasterQuery, distributeVO, distributeConfigDRO);

		return distributeVO;
	}

}
